﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using A2DFramework.HttpLoadBalancer.Config;
using System.Net;

namespace A2DFramework.HttpLoadBalancer.Connection
{
    public class ConnectionMaster
    {
        private Socket socket;
        private ConfigInfo config;
        private bool serverClosed = false;

        public ConnectionMaster(int port, string contentServerUrl)
        {
            config = new ConfigInfo();
            config.Port = port;
            config.ContentServerUrl = contentServerUrl;

            serverClosed = false;

            socket = CreateSocketBindAndListen(AddressFamily.InterNetwork, IPAddress.Loopback, config.Port);
        }

        private void Listen(object state)
        {
            while (!serverClosed)
            {
                Socket clientSocket=socket.Accept();
                ConnectionWorker connection = ConnectionWorkerPool.GetOne(clientSocket);
                connection.ContentServerUrl = this.config.ContentServerUrl;

                if (!serverClosed)
                    ThreadPool.QueueUserWorkItem(new WaitCallback(connection.ProcessRequest));
            }
        }

        public void Start()
        {
            serverClosed = false;

            //启动监听线程
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.Listen));
        }





        private static Socket CreateSocketBindAndListen(AddressFamily family, IPAddress address, int port)
        {
            Socket socket = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socket.Bind(new IPEndPoint(address, port));
            socket.Listen((int)SocketOptionName.MaxConnections);
            return socket;
        }
    }
}
